import type { RouteRecordRaw } from 'vue-router'

export let firstMenu: any = null
export function mapMenus(userMenu: any) {
  const LoacalRoutes: RouteRecordRaw[] = [
    {
      path: '/main/analysis/dashboard',
      component: () => import('@/views/main/analysis/dashboard/dashboard.vue')
    },
    {
      path: '/main/analysis/overview',
      component: () => import('@/views/main/analysis/overview/overview.vue')
    },
    {
      path: '/main/product/category',
      component: () => import('@/views/main/product/category/category.vue')
    },
    {
      path: '/main/product/goods',
      component: () => import('@/views/main/product/goods/goods.vue')
    },
    {
      path: '/main/story/chat',
      component: () => import('@/views/main/story/chat/chat.vue')
    },
    {
      path: '/main/story/list',
      component: () => import('@/views/main/story/list/list.vue')
    },
    {
      path: '/main/system/department',
      component: () => import('@/views/main/system/department/department.vue')
    },
    {
      path: '/main/system/menu',
      component: () => import('@/views/main/system/menu/menu.vue')
    },
    {
      path: '/main/system/role',
      component: () => import('@/views/main/system/role/role.vue')
    },
    {
      path: '/main/system/user',
      component: () => import('@/views/main/system/user/user.vue')
    }
  ]

  const routes: RouteRecordRaw[] = []

  for (const menu of userMenu) {
    for (const key of menu.children) {
      let route = LoacalRoutes.find((item) => item.path === key.url)
      if (route) {
        // 1.给顶层菜单做一个重定向功能，
        if (!routes.find((item) => item.path === menu.url)) {
          routes.push({ path: menu.url, redirect: route.path })
        }
        // 2.二级菜单
        routes.push(route)
      }
      if (!firstMenu && route) {
        firstMenu = route
      }
    }
  }

  return routes
}

export function defaultMenu(path: string, userMenu: any) {
  for (const menu of userMenu) {
    for (const submenu of menu.children) {
      if (path === submenu.url) return submenu
    }
  }
}

export function mapCrumbs(path: string, userMenu: any) {
  const crumbsRoute: any[] = []
  for (const menu of userMenu) {
    for (const submenu of menu.children) {
      if (path === submenu.url) {
        // 1.将顶层菜单也添加进去
        crumbsRoute.push({ name: menu.name, path: menu.url })
        crumbsRoute.push({ name: submenu.name, path: submenu.url })
      }
    }
  }
  return crumbsRoute
}
